/*
 * @Author: 缄默
 * @Date: 2021-12-11 15:54:51
 * @LastEditors: 缄默
 * @LastEditTime: 2021-12-14 20:37:35
 */

//组合模式安全模式实现

#include <iostream>
#include <vector>

using namespace std;

class Component {
public:
    virtual void Operation() { }

    virtual void Add(const Component& com) { }

    virtual void Remove(const Component& com) { }

    virtual Component* GetChild(int index) {
        return 0;
    }

    virtual ~Component() { }
};

class Composite : public Component {
private:
    vector<Component*> _coms;

public:
    void Add(Component* com) {
        _coms.push_back(com);
    }

    void Operation() {
        cout << "Composite::Operation..." << endl;
        for (auto com : _coms) {
            com->Operation();
        }
    }

    void Remove(Component* com) {
        auto iter = _coms.begin();
        while (iter != _coms.end()) {
            if (*iter == com) {
                _coms.erase(iter);
                break;
            }
        }
    }

    Component* GetChild(int index) {
        return _coms[index];
    }
};

class Leaf : public Component {
public:
    void Operation() {
        cout << "Leaf::Operation..." << endl;
    }
};

int main() {
    Leaf *leaf = new Leaf();
    leaf->Operation();
    Composite *com = new Composite();
    com->Add(leaf);
    com->Operation();
    Component *leaf_ = com->GetChild(0);
    leaf_->Operation();

    delete leaf;
    delete com;

    return 0;
}